package com.hand.app.service.impl;

import com.hand.api.controller.v1.dto.SoHeaderDTO;
import com.hand.api.controller.v1.dto.SoHeaderRequestParam;
import com.hand.app.service.SoHeaderService;
import com.hand.domain.content.OrderStatus;
import com.hand.domain.entity.SoHeader;
import com.hand.domain.entity.SoLine;
import com.hand.domain.entityvo.SoLineVo;
import com.hand.domain.entityvo.SoOrderVo;
import com.hand.domain.repository.SoHeaderRepository;
import com.hand.domain.repository.SoLineRepository;
import com.hand.infra.mapper.SoHeaderMapper;
import io.choerodon.core.domain.Page;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.oauth.DetailsHelper;
import io.choerodon.mybatis.pagehelper.PageHelper;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.hzero.boot.platform.code.builder.CodeRuleBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 业务表应用服务默认实现
 */
@Service
public class SoHeaderServiceImpl implements SoHeaderService {

    @Resource
    private SoHeaderMapper soHeaderMapper;
    @Resource
    private SoHeaderRepository soHeaderRepository;
    @Resource
    private SoLineRepository soLineRepository;
    @Resource
    private CodeRuleBuilder codeRuleBuilder;

    /**
     * 订单汇总查询API
     * @param pageRequest
     * @param requestParam
     * @return
     */
    @Override
    public Page<SoHeaderDTO> queryOrderForAll(PageRequest pageRequest, SoHeaderRequestParam requestParam) {
        // 通过 Mapper 查询，PageHelper 模仿 HZero 平台操作
        return PageHelper.doPageAndSort(pageRequest, () -> soHeaderMapper.queryOrderForAll(requestParam));
    }

    /**
     * 订单删除API
     * @param soHeader
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrderHeader(SoHeader soHeader) {
        SoHeader soHeader_exist = soHeaderRepository.selectByPrimaryKey(soHeader.getSoHeaderId());
        if (soHeader_exist == null){
            throw new CommonException("单据不存在！");
        }
        if (!soHeader_exist.getCreatedBy().equals(DetailsHelper.getUserDetails().getUserId())){
            throw new CommonException("您和单据创建者身份不一致！");
        }
        // 判断订单状态是否为 new 或者 rejected
        if (!OrderStatus.NEW.equals(soHeader.getOrderStatus()) && !OrderStatus.REJECTED.equals(soHeader.getOrderStatus())){
            throw new CommonException("单据状态不为NEW 或 REJECTED！");
        }
        // 一个订单头对应多个订单行，根据订单头删除对应订单行，最后删除订单头
        List<SoLine> soLines = soLineRepository.select(SoLine.FIELD_SO_HEADER_ID, soHeader.getSoHeaderId());
        if (soLines.size() > 0){
            for (SoLine s : soLines){
                soLineRepository.deleteByPrimaryKey(s.getSoLineId());
            }
        }
        soHeaderRepository.deleteByPrimaryKey(soHeader.getSoHeaderId());
    }

    /**
     * 订单保存API
     * @param soOrderVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrder(SoOrderVo soOrderVo) {
        // 订单头为空执行插入操作,否则执行更新操作
        if(soOrderVo.getSoHeaderId() == null){
            String data = "2020-12-30";
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try{
                // 判断日期是否不小于2020年 如果超过2020 12 30  不能创建订单
                if(soOrderVo.getOrderDate().compareTo(format.parse(data)) < 0){
                    throw new CommonException("无法创建当前日期订单！");
                }
            }catch (Exception e){
                e.getStackTrace();
            }
            // flag 为 0 执行插入操作，
            insertOrUpdate(soOrderVo,0);

        }else {
            // 判断订单状态是否为 new 或者 rejected
            if (!soOrderVo.getOrderStatus().equals(OrderStatus.NEW) && !soOrderVo.getOrderStatus().equals(OrderStatus.REJECTED)){
                throw new CommonException("单据状态不为NEW 或 REJECTED！");
            }
            // flag 为 1 执行更新操作
            insertOrUpdate(soOrderVo,1);
        }
    }

    private void insertOrUpdate(SoOrderVo soOrderVo,int flag) {
        String orderCode = codeRuleBuilder.generateCode("HZERO.29759.ORDER.NUMBER", null);
        SoHeader soHeader = new SoHeader();
        if (flag == 1){
            soHeader = soHeaderRepository.selectByPrimaryKey(soOrderVo.getSoHeaderId());
        }
        soHeader.setOrderNumber(orderCode);
        soHeader.setCompanyId(soOrderVo.getCompanyId());
        soHeader.setOrderDate(soOrderVo.getOrderDate());
        soHeader.setOrderStatus("NEW");
        soHeader.setCustomerId(soOrderVo.getCustomerId());
        if(flag == 0){
            soHeaderRepository.insert(soHeader);
        }else {
            System.out.println("===========================>" +soHeader.getObjectVersionNumber());
            soHeaderRepository.updateByPrimaryKey(soHeader);
        }
        if (soOrderVo != null && soOrderVo.getSoLineVoList().size() > 0){
            for(SoLineVo soLineVo : soOrderVo.getSoLineVoList()){
                SoLine soLine = soLineRepository.selectByPrimaryKey(soLineVo.getSoLineId());
                if (soLine == null){
                    break;
                }
                soLine.setOrderQuantity(soLineVo.getOrderQuantity());
                soLine.setSoHeaderId(soHeader.getSoHeaderId());
                soLine.setOrderQuantityUom(soLineVo.getOrderQuantityUom());
                soLine.setUnitSellingPrice(soLineVo.getUnitSellingPrice());
                if(flag == 0){
                    soLineRepository.insert(soLine);
                }else {
                    soLineRepository.updateByPrimaryKey(soLine);
                }
            }
        }
    }
}
